# -*- coding: UTF-8 -*-
import re

import signal
from scrapy import signals
import logging
import scrapy
import traceback
from scrapy.selector import Selector
from scrapy.http import Request
from pangolin.common.date_common import DateCommon
from pangolin.spider_enum.companyCodeEnum import getCompanyCode
from pangolin.common.db_operateCommon import *
from pangolin.common.string_common import StringCommon
from pangolin.items import TicketDetailItem
from multiprocessing import Process
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from pangolin.common.http_common import *
from pangolin.settings import IS_SAVE_SERVER
from pangolin.settings import IS_SNAPSHOT
import sys, os
from PIL import Image
from datetime import *
import time

reload(sys)
sys.setdefaultencoding('UTF-8')


class PangolinSpider(scrapy.Spider):
    name = 'xc_ticket_by_url_spider'
    allowed_domain = 'ctrip.com'  # 允许爬虫运行的域

    def __init__(self, crawler, spider_name, city_code, company_code, task_id, task_date, timer_param,
                 timer_granularity, timer_id, url, lv_product_id, miss_product_flag):
        # 接受入参,全局引用
        self.save_server = IS_SAVE_SERVER
        self.snapshot = IS_SNAPSHOT

        self.spider_name = spider_name
        self.city_code = city_code
        self.company_code = company_code
        self.task_id = task_id
        self.task_date = task_date
        self.timer_param = timer_param
        self.timer_granularity = timer_granularity
        self.timer_id = timer_id
        self.url = url
        self.lv_product_id = lv_product_id
        self.miss_product_flag = miss_product_flag
        # 爬虫爬取前先删除同一批次同一城市的数据
        if miss_product_flag == 'FALSE':
            db_operate = DbOperateClass()
            db_operate.delete_pd_and_cd_data("ticket_pdetail_xc", "ticket_cdetail_xc", getCompanyCode(company_code),
                                             city_code, task_id, task_date)
        self.crawler = crawler
        # 绑定爬虫开始和结束信号，便于监听爬虫开始与结束
        cs = crawler.signals
        cs.connect(self.spider_closed, signals.spider_closed)
        cs.connect(self.spider_opened, signals.spider_opened)

    def start_requests(self):
        # 查询需要爬取的产品URL
        db_operate = DbOperateClass()
        urls = []
        lv_product_ids = {}
        if self.miss_product_flag == 'FALSE':
            sql = "SELECT xc_url,product_id FROM cpa_care_product WHERE city_code = '" + self.city_code + "' AND business_code='TICKET'"
            try:

                (fc, count) = db_operate.select_by_sql(sql)
                for row in fc:
                    if row[0] is not None and row[0] != '':
                        url = row[0]
                        lv_product_id = row[1]
                        lv_product_ids.setdefault(url, lv_product_id)
                        urls.append(url)
                self.lv_product_ids = lv_product_ids
            except Exception as e:
                logging.info("Exception %s" % e)
                raise
        else:
            lv_product_ids.setdefault(self.url, self.lv_product_id)
            self.lv_product_ids = lv_product_ids
            urls.append(self.url)
        for url in urls:
            self.count = 0
            yield Request(url, dont_filter=True)

    def parse(self, response):  # 页面解析函数，这里必须为parse()
        response_url = response.url
        if response_url.find('main.aspx') > -1:
            url = response_url.split("returnurl=")[1].split("&bgref")[0].replace("%3a", ":").replace("%2f", "/")
            # 遇到验证码，尝试重新访问原URL且最多不超过两次。访问两次原URL还是触发验证码机制，直接访问验证通过后的URL
            if self.count < 2:
                self.count += 1
                url = url.replace("Thingstodo-Booking-ShoppingWebSite/dest", "dest")
                yield Request(url, callback=self.parse, dont_filter=True)
            else:
                self.count = 0
                # url = self.url.replace("dest", "Thingstodo-Booking-ShoppingWebSite/dest")
                yield Request(url, dont_filter=True)
        else:
            sels = Selector(response)
            try:
                item = TicketDetailItem()
                item['type'] = "TICKET"
                item['timer_param'] = self.timer_param
                item['timer_granularity'] = self.timer_granularity
                item['business_type'] = "ticket"

                item['product_table'] = "ticket_pdetail_xc"
                item['data_type'] = "TicketDetail"
                item['detail_id'] = DateCommon.get_id_by_datetime()
                item['company_code'] = getCompanyCode(self.company_code)
                item['platform_code'] = "PC"  # 操作平台WAP，PC
                item['city_code'] = self.city_code
                item['scenery_name'] = StringCommon.remove_blank(
                    sels.xpath('//*[@class="media-title"]/text()').extract()[0])  # 景点名称
                item['scenery_addr'] = StringCommon.remove_blank(
                    sels.xpath('//*[@id="media-wrapper"]/div[2]/ul/li[1]/span/text()').extract()[0])  # 景点地址
                item['product_id'] = response.body.split("productid: ")[1].split(",")[0]
                item['detail_url'] = response.url  # 详情页链接
                # 产品详情
                item['lowest_price'] = StringCommon.remove_blank(
                    sels.xpath('//*[@id="media-wrapper"]/div[3]/div/span/text()').extract()[0])  # 最低价
                item['score'] = sels.xpath('//*[@id="J-grade"]/i/text()').extract()[0]  # 评分
                image_num = sels.xpath('//*[@id="J-Jdjj"]').extract()[0]
                item['image_num'] = image_num.count("<img")
                introduction_tag = sels.xpath('//*[@id="media-wrapper"]/div[2]/ul/li[2]/span/text()').extract()
                item['introduction'] = StringCommon.remove_blank(
                    introduction_tag[0]) if introduction_tag else ""  # 使用说明
                score_tag = StringCommon.remove_blank(sels.xpath('//*[@class="t-comments"]').extract()[0])  # 评分标签，印象
                dr = re.compile(r'<[^>]+>', re.S)
                score_tag = dr.sub('', score_tag)
                item['score_tag'] = score_tag
                star_level_tag = response.css('.media-right > strong')
                if star_level_tag:
                    star_level_tag = sels.xpath('//*[@id="media-wrapper"]/div[2]/span/strong/text()').extract()[0]  # 星级
                else:
                    star_level_tag = ""  # 星级
                if star_level_tag.count("A") > 0:
                    item['star_level'] = str(star_level_tag.count("A")) + "A"
                else:
                    item['star_level'] = ""
                item['create_time'] = DateCommon.get_current_date()
                item['update_time'] = item['create_time']
                item['task_id'] = self.task_id
                item['task_date'] = self.task_date
                # db_operate = DbOperateClass()
                # sql = "SELECT product_id FROM cpa_care_product WHERE xc_url like '%" + response.url + "%'"
                # logging.info("SELECT_product_id_SQL:%s" % sql)
                # data = db_operate.select_one_by_sql(sql)
                # if data[0] is not None:
                #     lv_product_id = data[0]
                # else:
                #     lv_product_id = ""
                url = response.url.replace("Thingstodo-Booking-ShoppingWebSite/dest", "dest")
                item['lv_product_id'] = self.lv_product_ids.get(url)
                if self.snapshot == 'TRUE':
                    # 获得截图地址
                    compress_path = self.save_screenshot(response, item['product_id'], self.city_code,
                                                         self.company_code, self.task_id, self.task_date)
                    item['snapshot_addr'] = compress_path
                else:
                    item['snapshot_addr'] = " "
                # 商品详情
                item['commodity_table'] = "ticket_cdetail_xc"
                item['commodity_type'] = []  # 商品类型或名称
                item['commodity_id'] = []  # 商品id
                item['commodity_name'] = []  # 商品名称
                item['commodity_url'] = []  # 商品名称
                item['sale_cond'] = []  # 提前时间、销售条件
                item['refund_cond'] = []  # 退改条件
                item['rack_rate'] = []  # 门市价
                item['sale_price'] = []  # 售价
                item['preferential'] = []  # 优惠
                item['price_list_id'] = ""
                item['booking_effective_time'] = []
                sites_evens = sels.css('tbody tr.ticket-info')
                if sites_evens:
                    commodity_type = ""
                    for i, sites in enumerate(sites_evens):
                        cmodity_type_tag = sites.css('td.ticket-type')
                        if cmodity_type_tag:
                            commodity_type = StringCommon.remove_blank(
                                sites.css('td.ticket-type > span::text').extract()[0])
                            sale_cond = StringCommon.remove_blank(
                                sites.css('.ticket-info > td:nth-child(3)::text').extract()[0])
                        else:
                            commodity_type = commodity_type
                            sale_cond = StringCommon.remove_blank(
                                sites.css('.ticket-info > td:nth-child(2)::text').extract()[0])
                        commodity_name = StringCommon.remove_blank(
                            sites.css('a.ticket-title').xpath('text()').extract()[0])
                        commodity_id = sites.css('.ticket-info').xpath('@data-id').extract()[0]
                        scenic_id = response.body.split("dest/t")[1].split(".html")[0]
                        commodity_url = "http://piao.ctrip.com/Thingstodo-Booking-bookingwebsite/TicketOrderInput?scenicID=" + str(
                            scenic_id) + "&productID=" + str(item['product_id']) + "&ticketID=" + str(commodity_id)
                        rack_rate_tag = sites.css('td.del-price > strong')
                        if rack_rate_tag:
                            rack_rate = StringCommon.remove_blank(sites.css('td.del-price > strong::text').extract()[0])
                        else:
                            rack_rate = ""
                        sale_price = StringCommon.remove_blank(
                            sites.css('span.ctrip-price > strong::text').extract()[0])
                        preferential = StringCommon.remove_blank(sites.css('div.icon-wrapper::text').extract()[0])
                        relative_url = "http://piao.ctrip.com/Thingstodo-Booking-ShoppingWebSite/api/TicketStatute?resourceID={}".format(
                            commodity_id)
                        # 增加重试逻辑，避免调用接口失败导致整个任务失败
                        attempts = 0
                        success = False
                        while attempts < 3 and not success:
                            try:
                                (refund_cond, booking_effective_time) = self.parse_commodity(relative_url, response)
                                success = True
                            except Exception as e:
                                refund_cond = ""
                                booking_effective_time = ""
                                logging.error("request调用携程接口抛出异常：%s，准备第%s次重试" % (e, attempts + 1))
                                logging.error(
                                    "xc_ticket_request_Exception: %s" % traceback.format_exc().replace("\"", "'"))
                                attempts += 1
                                if attempts == 3:
                                    break
                        item['commodity_type'].append(commodity_type)  # 商品类型或名称
                        item['commodity_id'].append(commodity_id)  # 商品id
                        item['commodity_name'].append(commodity_name)  # 商品名称
                        item['commodity_url'].append(commodity_url)  # 商品链接
                        item['sale_cond'].append(sale_cond)  # 提前时间、销售条件
                        item['refund_cond'].append(refund_cond)  # 退改条件
                        item['booking_effective_time'].append(booking_effective_time)
                        item['rack_rate'].append(rack_rate)  # 门市价
                        item['sale_price'].append(sale_price)  # 售价
                        item['preferential'].append(preferential)  # 优惠
                    yield item
                else:
                    yield item

            except Exception as e:
                db_operate = DbOperateClass()
                logging.error("记录日志：标签变动 %s ,%s" % (response.url, e))
                logging.info("页面源码：%s ,%s" % (response.url, response.body))
                logging.error(
                    "xc_ticket_by_url_spider_Exception: %s" % traceback.format_exc().replace("\"", "'"))
                # 错误描述只截取前500个字符，剩下的用***代替
                error_desc = traceback.format_exc().replace("\"", "'").replace(" ", "")
                if len(error_desc) > 500:
                    error_desc = error_desc[:500] + '***'
                # 错误日志记入日志表
                sql = "insert into cpa_oper_log (log_type,company_code,busi_type,url,batch_num,timer_code,error_code,error_desc,task_id,task_date) values (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\" ,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")" \
                      % ("C", getCompanyCode(self.company_code), "门票", response.url, self.task_date, "timer_code",
                         "error_code", error_desc, str(self.task_id), str(self.task_date))
                db_operate.update_by_sql(sql)
                if self.save_server == 'TRUE':
                    http_common = HttpCommon()
                    operate_log = {'type': 'LOG',
                                   'log_type': "C",
                                   'company_code': getCompanyCode(self.company_code),
                                   'busi_type': "门票",
                                   'url': response.url,
                                   'batch_num': self.task_date,
                                   'timer_code': "timer_code",
                                   'error_code': "error_code",
                                   'error_desc': error_desc,
                                   'task_id': str(self.task_id),
                                   'task_date': str(self.task_date)}
                    http_common.get_method(operate_log)

    def parse_commodity(self, url, response):
        headers = {
            'Host': "piao.ctrip.com",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "en-US,en;q=0.5",
            "Connection": "keep-alive",
            "User-Agent": response.request.headers['User-Agent']
        }
        proxies = {
            "http": response.meta['proxy'],
        }
        response = requests.get(url, headers=headers, timeout=20, proxies=proxies).text
        commodity_statute_list = json.loads(response)
        refund_cond = ""
        booking_effective_time = ""
        for commodity_statute in commodity_statute_list['data']:
            if '退改规则' == commodity_statute['title']:
                refund_cond = commodity_statute['desc'].replace("<br/>", "")
            if '预订时间' == commodity_statute['title']:
                booking_effective_time = commodity_statute['desc'].split('，')[1].replace("<br/>", "") if \
                commodity_statute['desc'].find('，') > -1 else commodity_statute['desc']

        return refund_cond, booking_effective_time

        # 按元素截图
    def save_screenshot(self, response, product_id, city_code, company_code, task_id, task_date):
        compress_path = ""
        try:
            file_name = getCompanyCode(
                company_code) + "__" + city_code + "__" + task_id + "__" + task_date + "__" + product_id + ".png"
            service_args = [
                '--proxy=' + response.meta['proxy'],
                '--load-images=no', ]
            dcap = dict(DesiredCapabilities.PHANTOMJS)
            # # 伪造ua信息
            # dcap["phantomjs.page.settings.userAgent"] = (request.headers['User-Agent'])
            dcap["phantomjs.page.settings.resourceTimeout"] = 5000  # 超时
            # 添加头文件
            dcap["phantomjs.page.customHeaders.Referer"] = (response.url)
            driver = webdriver.PhantomJS(desired_capabilities=dcap, service_args=service_args)  # 线上使用方式
            logging.info("%s PhantomJS is getUrl..." % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            driver.set_page_load_timeout(100)
            driver.set_script_timeout(100)
            driver.get(response.url)

            # 截图
            path = os.getcwd() + "/screenshot/" + file_name
            logging.info("%s save_screenshot is starting..." % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            driver.save_screenshot(path)
            logging.info("%s save_screenshot is end..." % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

            # 根据元素获得裁剪区域的坐标
            element = driver.find_element_by_xpath("//*[@id='media-wrapper']")
            element1 = driver.find_element_by_xpath("//*[@id='booking-wrapper']")
            left = int(100 + element.location['x'])
            top = int(element.location['y'])
            right = int(100 + element.location['x'] + element.size['width'])
            bottom = int(element.location['y'] + element.size['height'] + element1.size['height'])
            # 根据获得的裁剪区域坐标截图
            compress_path = os.getcwd() + "/compressImage/" + file_name
            im = Image.open(path)
            im = im.crop((left, top, right, bottom))  # (left, top, right, bottom)
            im.save(compress_path)
            os.remove(path)
        except Exception as e:
            logging.error("截图失败 %s ,%s" % (response.url, e))
        finally:
            try:
                driver.service.process.send_signal(signal.SIGTERM)
                driver.quit()
            except Exception as e:
                logging.error("driver.quit_failed %s" % e)
        return compress_path

    @classmethod
    def from_crawler(cls, crawler, **kwargs):
        logging.info('inside_from_crawler: ')
        if kwargs['miss_product_flag'] == 'FALSE':
            kwargs['url'] = ''
            kwargs['lv_product_id'] = ''
        else:
            kwargs['timer_granularity'] = ''
            kwargs['timer_id'] = ''

        return cls(
            crawler,
            spider_name=kwargs['spider_name'],
            city_code=kwargs['city_code'],
            company_code=kwargs['company_code'],
            task_id=kwargs['task_id'],
            task_date=kwargs['task_date'],
            timer_param=kwargs['timer_param'],
            timer_granularity=kwargs['timer_granularity'],
            timer_id=kwargs['timer_id'],
            url=kwargs['url'],
            lv_product_id=kwargs['lv_product_id'],
            miss_product_flag=kwargs['miss_product_flag']
        )

    def spider_opened(self, spider):
        logging.info('Spider_opened_list: %s' % spider.name)
        # 爬虫设为启动状态2
        db_operate = DbOperateClass()
        db_operate.update_status(2, "PYTHON", self.timer_id)

    def spider_closed(self, spider, reason):
        logging.info('spider_closed_detail: %s ,reason:%s' % (spider.name, reason))
        db_operate = DbOperateClass()
        if self.miss_product_flag == 'TRUE':  # 补录
            db_operate.update_miss_status(1, self.url, self.task_id)
        else:
            sql = "SELECT timer.timer_status FROM cpa_timer timer WHERE timer.timer_type='PYTHON' " \
                  "AND timer.timer_id = '" + self.timer_id + "'"
            (fc, count) = db_operate.select_by_sql(sql)
            spider.logger.info('SELECT_COUNT: %s ,SQL:%s' % (count, sql))
            timer_status = ""
            for row in fc:
                timer_status = row[0]
            logging.info("timer_status:%s" % timer_status)
            if timer_status == '2':
                db_operate.update_status(5, "PYTHON", self.timer_id)
